package main

import (
	"fmt"
	"log"
	"math/rand"
	"net/http"

	"gitee.com/kessil/chicory/dist"
	"gitee.com/kessil/chicory/internal/config"
	"gitee.com/kessil/chicory/internal/repositories"
	"gitee.com/kessil/chicory/internal/utils"
	"go.uber.org/zap"
	"xorm.io/xorm"

	// "gitee.com/kessil/chicory/internal/middleware"
	"gitee.com/kessil/chicory/internal/models"
	"gitee.com/kessil/chicory/internal/routers"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
)

func main() {
	// 加载配置
	cfg, err := config.LoadConfig("config.toml")
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}

	// 初始化工具logger
	utils.InitLogger()
	utils.Info("Application starting", zap.String("version", "1.0.0"))

	// 初始化数据库
	db, err := config.InitDB(cfg)
	if err != nil {
		log.Fatalf("Failed to init database: %v", err)
	}
	defer db.Close()

	// 初始化表结构
	if err := models.InitModels(db); err != nil {
		log.Fatalf("Failed to init models: %v", err)
	}

	// mock 数据
	MockSQL(db)

	// 创建路由
	r := chi.NewRouter()

	// 添加中间件
	r.Use(middleware.Logger)
	r.Use(middleware.Recoverer)
	r.Use(middlewareCors)

	// 设置路由
	routers.SetupRoutes(r, db, cfg, dist.DistFolder)

	// 启动服务器
	utils.Info("Server starting", zap.Int("port", cfg.Server.Port))
	if err := http.ListenAndServe(fmt.Sprintf(":%d", cfg.Server.Port), r); err != nil {
		utils.Fatal("Failed to start server", zap.Error(err))
	}
}

func middlewareCors(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}

		next.ServeHTTP(w, r)
	})
}

func MockSQL(db *xorm.Engine) {
	roleRepo := mockRoles(db)

	userRepo := mockUsers(db)

	userRepo.AddUserRole(1, 1)

	mockPermissions(db)
	// INSERT INTO `profile` VALUES (1, NULL, '', NULL, NULL, 1, 'Admin');
	// db.Table("profile").Insert(&models.Profile{
	// 	Avatar:   "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80",
	// 	UserId:   1,
	// 	Nickname: "管理员",
	// })

	roleRepo.AddRolePermission(1, 1)
	roleRepo.AddRolePermission(1, 2)
	roleRepo.AddRolePermission(1, 3)
	roleRepo.AddRolePermission(1, 4)
	roleRepo.AddRolePermission(1, 5)
	roleRepo.AddRolePermission(1, 6)
	roleRepo.AddRolePermission(1, 7)
	roleRepo.AddRolePermission(1, 8)
	roleRepo.AddRolePermission(1, 9)
	roleRepo.AddRolePermission(1, 10)
	roleRepo.AddRolePermission(1, 11)
	roleRepo.AddRolePermission(1, 12)
	roleRepo.AddRolePermission(1, 13)
	roleRepo.AddRolePermission(1, 14)
	roleRepo.AddRolePermission(1, 15)

	mockAssets(db)

	mockDesks(db)
}

func mockAssets(db *xorm.Engine) {
	assetRepo := repositories.NewAssetRepository(db)
	assets := []models.Asset{
		{Name: "中国铁路南昌局集团有限公司"},
		{Name: "东南沿海铁路福建有限责任公司(福州段)"},
		{Name: "龙岩铁路有限责任公司普速(福州段)"},
		{Name: "龙岩铁路有限责任公司(福州段)"},
		{Name: "向莆铁路股份有限公司(福州段)"},
		{Name: "赣龙复线铁路有限责任公司(福州段)"},
		{Name: "福建福平铁路有限责任公司(福州段)"},
		{Name: "泉州铁路有限责任公司(福州段)"},
		{Name: "武夷山铁路有限责任公司(福州段)"},
		{Name: "福建湄洲湾港口铁路支线有限责任公司"},
		{Name: "福州江阴港铁路支线有限责任公司"},
		{Name: "福建可门港铁路支线有限责任公司"},
		{Name: "厦门国际物流港有限责任公司"},
		{Name: "福建湄洲湾南岸铁路支线有限责任公司"},
	}
	for _, asset := range assets {
		assetRepo.Create(&asset)
	}
}

func mockDesks(db *xorm.Engine) {
	repo := repositories.NewDeskRepository(db)
	items := []models.Desk{
		{Name: "温福台", Code: "", Pinyin: "WF"},
		{Name: "福州枢纽台", Code: "", Pinyin: "FZSN"},
		{Name: "福厦台", Code: "", Pinyin: "FX"},
		{Name: "厦深台", Code: "", Pinyin: "XS"},
		{Name: "南龙台", Code: "", Pinyin: "NL"},
		{Name: "建福台", Code: "", Pinyin: "JF"},
		{Name: "赣龙台", Code: "", Pinyin: "GL"},
		{Name: "三泉台", Code: "", Pinyin: "SQ"},
		{Name: "兴三台", Code: "", Pinyin: "XS"},
		{Name: "福厦高铁台", Code: "", Pinyin: "FXGT"},
		{Name: "鹰来台", Code: "", Pinyin: "YL"},
		{Name: "来福台", Code: "", Pinyin: "LF"},
		{Name: "来漳台", Code: "", Pinyin: "LZ"},
		{Name: "漳厦台", Code: "", Pinyin: "ZX"},
	}
	for _, item := range items {
		repo.Create(&item)
	}
}

func mockUsers(db *xorm.Engine) *repositories.UserRepository {
	userRepo := repositories.NewUserRepository(db)
	users := []models.User{
		{
			Username: "admin",
			Email:    "admin@chichory.com",
			Password: "123456",
			Avatar:   "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80",
			Nickname: "管理员",
		},
		{
			Username: "user",
			Email:    "user@chichory.com",
			Password: "123456",
			Avatar:   "",
			Nickname: "用户",
		},
	}

	for _, user := range users {
		// if err := user.SetPassword(user.Password); err != nil {
		// 	return
		// }
		userRepo.Create(&user)
	}
	for i := range 15 {
		userRepo.Create(&models.User{
			Username: fmt.Sprintf("Name_%d", i),
			Password: "123456",
			Avatar:   "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80",
			Nickname: fmt.Sprintf("用户%d", i),
		})
	}
	return userRepo
}

func mockRoles(db *xorm.Engine) *repositories.RoleRepository {
	roleRepo := repositories.NewRoleRepository(db)
	roles := []models.Role{
		{
			Code:   "SUPER_ADMIN",
			Name:   "超级管理员",
			Enable: true,
		},
		{
			Code:   "ADMIN",
			Name:   "管理员",
			Enable: true,
		},
		{
			Code:   "User",
			Name:   "用户",
			Enable: true,
		},
	}
	for _, role := range roles {
		roleRepo.Create(&role)
	}
	for i := range 15 {
		roleRepo.Create(&models.Role{
			Code:   fmt.Sprintf("User_%d", i),
			Name:   fmt.Sprintf("Name_%d", i),
			Enable: rand.Float64() > 0.5,
		})
	}
	return roleRepo
}

func mockPermissions(db *xorm.Engine) {
	perRepo := repositories.NewPermissionRepository(db)
	permissions := []*models.Permission{
		// 系统管理：资源管理、角色管理、用户管理
		// 基础功能：图标Icon、基础组件、Unocss、KeepAlive、Modal
		// 业务示例：图片上传
		{
			Name:   "系统管理",
			Code:   "SysMgt",
			Type:   "MENU",
			Icon:   "i-fe:grid",
			Show:   true,
			Enable: true,
			Order:  0,
		},
		{
			Name:      "资源管理",
			Code:      "Resource_Mgt",
			Type:      "MENU",
			ParentId:  1,
			Path:      "/pms/resource",
			Redirect:  "",
			Icon:      "i-fe:list",
			Component: "/src/views/pms/resource/index.vue",
			Show:      true,
			Enable:    true,
			Order:     0,
		},
		{
			Name:      "角色管理",
			Code:      "RoleMgt",
			Type:      "MENU",
			ParentId:  1,
			Path:      "/pms/role",
			Icon:      "i-fe:user-check",
			Component: "/src/views/pms/role/index.vue",
			Show:      true,
			Enable:    true,
			Order:     1,
		},
		{
			Name:      "用户管理",
			Code:      "UserMgt",
			Type:      "MENU",
			ParentId:  1,
			Path:      "/pms/user",
			Icon:      "i-fe:user",
			Component: "/src/views/pms/user/index.vue",
			KeepAlive: false,
			Show:      true,
			Enable:    true,
			Order:     2,
		},
		{
			Name:   "基础功能",
			Code:   "Base",
			Type:   "MENU",
			Icon:   "i-fe:grid",
			Show:   true,
			Enable: true,
			Order:  1,
		},
		{
			Name:      "图标 Icon",
			Code:      "Icon",
			Type:      "MENU",
			ParentId:  5,
			Path:      "/base/icon",
			Icon:      "i-fe:feather",
			Component: "/src/views/base/unocss-icon.vue",
			Show:      true,
			Enable:    true,
			Order:     0,
		},
		{
			Name:      "基础组件",
			Code:      "BaseComponents",
			Type:      "MENU",
			ParentId:  5,
			Path:      "/base/components",
			Icon:      "i-me:awesome",
			Component: "/src/views/base/index.vue",
			Show:      true,
			Enable:    true,
			Order:     1,
		},
		{
			Name:      "Unocss",
			Code:      "Unocss",
			Type:      "MENU",
			ParentId:  5,
			Path:      "/base/unocss",
			Icon:      "i-me:awesome",
			Component: "/src/views/base/unocss.vue",
			Show:      true,
			Enable:    true,
			Order:     2,
		},
		{
			Name:      "KeepAlive",
			Code:      "KeepAlive",
			Type:      "MENU",
			ParentId:  5,
			Path:      "/base/keep-alive",
			Icon:      "i-me:awesome",
			Component: "/src/views/base/keep-alive.vue",
			Show:      true,
			Enable:    true,
			Order:     3,
		},
		{
			Name:      "MeModal",
			Code:      "TestModal",
			Type:      "MENU",
			ParentId:  5,
			Path:      "/testModal",
			Icon:      "i-me:dialog",
			Component: "/src/views/base/test-modal.vue",
			Show:      true,
			Enable:    true,
			Order:     4,
		},

		{
			Name:   "业务示例",
			Code:   "Demo",
			Type:   "MENU",
			Icon:   "i-fe:grid",
			Show:   true,
			Enable: true,
			Order:  2,
		},
		{
			Name:      "图片上传",
			Code:      "ImgUpload",
			Type:      "MENU",
			ParentId:  11,
			Path:      "/demo/upload",
			Icon:      "i-fe:image",
			Component: "/src/views/demo/upload/index.vue",
			KeepAlive: false,
			Show:      true,
			Enable:    true,
			Order:     0,
		},

		{
			Name:   "专业管理",
			Code:   "Ledger",
			Type:   "MENU",
			Icon:   "i-fe:slack",
			Show:   true,
			Enable: true,
			Order:  3,
		},
		{
			Name:      "资产性质",
			Code:      "Asset",
			Type:      "MENU",
			ParentId:  13,
			Path:      "/ledger/asset",
			Icon:      "i-fe:image",
			Component: "/src/views/ledger/asset/index.vue",
			KeepAlive: false,
			Show:      true,
			Enable:    true,
			Order:     0,
		},
		{
			Name:      "调度台",
			Code:      "Desk",
			Type:      "MENU",
			ParentId:  13,
			Path:      "/ledger/desk",
			Icon:      "i-fe:image",
			Component: "/src/views/ledger/desk/index.vue",
			KeepAlive: false,
			Show:      true,
			Enable:    true,
			Order:     1,
		},

		{
			Name:      "分配用户",
			Code:      "RoleUser",
			Type:      "MENU",
			ParentId:  3,
			Path:      "/pms/role/user/:roleId",
			Icon:      "i-fe:user-plus",
			Component: "/src/views/pms/role/role-user.vue",
			Show:      false,
			Enable:    true,
			Order:     99,
		},
		{
			Name:      "个人资料",
			Code:      "UserProfile",
			Type:      "MENU",
			Path:      "/demo/upload",
			Icon:      "i-fe:user",
			Component: "/src/views/profile/index.vue",
			Show:      false,
			Enable:    true,
			Order:     99,
		},

		{
			Name:     "创建新用户",
			Code:     "AddUser",
			Type:     "BUTTON",
			ParentId: 4,
			Show:     true,
			Enable:   true,
			Order:    1,
		},
	}
	for _, v := range permissions {
		perRepo.Create(v)
	}
}
